package com.xiyang.operater.controller;

import cn.hutool.core.codec.Base64;
import com.xiyang.operater.VO.ImgVO;
import com.xiyang.operater.VO.LoginUserVO;
import com.xiyang.operater.common.BaseResult;
import com.xiyang.operater.common.ReturnCode;
import com.xiyang.operater.repository.UserRepository;
import com.xiyang.operater.utils.UUIDUtil;
import com.xiyang.operater.utils.VerifyCodeUtil;
import org.springframework.util.Base64Utils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;

import java.util.Map;

/**
 * @author xiyang.ycj
 * @since Jun 22, 2019 00:19:37 AM
 */
@RestController
public class MainController {

    private final UserRepository userRepository;

    public MainController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    @PostMapping("/123")
    public Object login(@RequestBody LoginUserVO user){
        return userRepository.findAll().get(0);
    }




    @GetMapping("/getCode")
    public Object getCode(HttpServletRequest request) throws IOException {

        /* 生成验证码字符串 */
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
        String uuid = UUIDUtil.GeneratorUUIDOfSimple();


        HttpSession session = request.getSession();
        session.setAttribute(uuid,verifyCode);

        int w = 111,h = 36;

        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            VerifyCodeUtil.outputImage(w, h, stream, verifyCode);
            return new BaseResult(ReturnCode.SUCCESS.getCode(),ReturnCode.SUCCESS.getMessage(),new ImgVO("data:image/gif;base64,"+Base64Utils.encodeToString(stream.toByteArray()),uuid));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        /* 生成验证码字符串 */
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
        String uuid = UUIDUtil.GeneratorUUIDOfSimple();

        int w = 111,h = 36;

        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            VerifyCodeUtil.outputImage(w, h, stream, verifyCode);
          // String encode =(Base64.getEncoder().encode(stream.toByteArray())).toString() ;

           String encode = Base64Utils.encodeToString(stream.toByteArray()) ;
            System.out.println(encode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
